package xj.graph2d.command;

import java.awt.geom.Rectangle2D;

import xj.graph2d.Command;
import xj.graph2d.DrawShape;
import xj.graph2d.SimpleDrawDocument;

public class SubshapeAuxAction implements Command.AuxAction {

  public static final int ATTACH_SUBSHAPE = 1;

  public static final int DETACH_SUBSHAPE = 2;

  public static final int DETACH_ATTACH_SUBSHAPE = 3;

  public SubshapeAuxAction(SimpleDrawDocument doc, DrawShape fromParent,
			   DrawShape toParent, DrawShape shape, int action) {
    this.doc = doc;
    this.fromParent = fromParent;
    this.toParent = toParent;
    this.shape = shape;
    this.action = action;
  }

  public void forward() {
    if (doc != null && shape != null) {
      Rectangle2D r2 = shape.getRepaintRect();
      switch (action) {
      case ATTACH_SUBSHAPE:
	if (toParent != null) {
	  doc.remove(shape);
	  toParent.addShape(shape);
	  doc.shapeAdded(shape);
	}
	break;

      case DETACH_SUBSHAPE:
	if (fromParent != null) {
	  fromParent.removeShape(shape);
	  doc.shapeRemoved(shape);
	  doc.add(shape);
	}
	break;

      case DETACH_ATTACH_SUBSHAPE:
	if (toParent != null && fromParent != null) {
	  fromParent.removeShape(shape);
	  doc.shapeRemoved(shape);
	  toParent.addShape(shape);
	  doc.shapeAdded(shape);
	}
	break;
      }
    }
  }

  public void backward() {
    if (doc != null && shape != null) {
      Rectangle2D r2 = shape.getRepaintRect();
      switch (action) {
      case ATTACH_SUBSHAPE:
	if (toParent != null) {
	  toParent.removeShape(shape);
	  doc.shapeRemoved(shape);
	  doc.add(shape);
	}
	break;

      case DETACH_SUBSHAPE:
	if (fromParent != null) {
	  doc.remove(shape);
	  fromParent.addShape(shape);
	  doc.shapeAdded(shape);
	}
	break;

      case DETACH_ATTACH_SUBSHAPE:
	if (toParent != null && fromParent != null) {
	  toParent.removeShape(shape);
	  doc.shapeRemoved(shape);
	  fromParent.addShape(shape);
	  doc.shapeAdded(shape);
	}
	break;
      }
    }
  }

  public boolean isAlwaysAfter() {
    return true;
  }

  SimpleDrawDocument doc;

  DrawShape fromParent;

  DrawShape toParent;

  DrawShape shape;

  int action;

}
